Implement strStr

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Solution:

  1. public class Solution {
  2. public int strStr(String haystack, String needle) {
  3. for (int i = 0; ; i++) {
  4. for (int j = 0; ; j++) {
  5. if (j == needle.length()) return i;
  6. if (i + j == haystack.length()) return -1;
  7. if (needle.charAt(j) != haystack.charAt(i + j)) break;
  8. }
  9. }
  10. }
  11. }